//
//  ScoreVC.swift
//  MM2
//
//  Created by 李成明 on 2021/12/31.
//

import UIKit
import CLImagePickerTool

private enum ScoreViewType {
    case single
    case pk
}

private class RankView: UIView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        layer.masksToBounds = true
        layer.cornerRadius = 10
        backgroundColor = .white
        clipsToBounds = false
        
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(clickAction))
        addGestureRecognizer(tap)
        
        addsubViews([rankIcon, rankLabel, titleLabel, avatar, userName, facecValue])
        
        titleLabel.frame = CGRect(x: 95, y: 5, width: 250, height: 20)
        rankIcon.frame = CGRect(x: 16, y: -15, width: 75, height: 75)
        
        var x = 100
        let y = 35
        rankLabel.frame = CGRect(x: x, y: y, width: 30, height: 30)
        x += (30 + 20)
        avatar.frame = CGRect(x: x, y: y, width: 35, height: 35)
        x += (35 + 20)
        userName.frame = CGRect(x: x, y: y, width: 70, height: 30)
        x += 70
        facecValue.frame = CGRect(x: x, y: y - 10, width: 100, height: 50)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    var user: User? {
        didSet {
            updateUI()
        }
    }
    
    private var clickColsure: ((RankView) -> Void)?
    
    private lazy var titleLabel: UILabel = {
        let view = UILabel()
        view.font = UIFont(name: "Helvetica-BoldOblique", size: 16)
        view.text = "排名     用户      用户名     颜值"
        return view
    }()
    
    private lazy var rankIcon: UIImageView = {
        let view = UIImageView()
        view.image = UIImage(named: "face_anly_rank_icon")
        return view
    }()
    
    private lazy var rankLabel: UILabel = {
        let view = UILabel()
        view.font = UIFont(name: faceValueFontStr, size: 25)
        view.text = "1"
        return view
    }()
    
    private lazy var avatar: UIImageView = {
        let view = UIImageView()
        view.layer.masksToBounds = true
        view.layer.cornerRadius = 12
        return view
    }()
    
    private lazy var userName: UILabel = {
        let view = UILabel()
        view.font = .systemFont(ofSize: 16)
        return view
    }()
    
    private lazy var facecValue: UILabel = {
        let view = UILabel()
        view.font = UIFont(name: faceValueFontStr, size: 25)
        view.textColor = faceValueColor
        return view
    }()
    
    
    private func updateUI() {
        guard let user = user else {  return }
        avatar.setAvatar(urlStr: user.avatar)
//        facecValue.text = "\(user?.faceValue ?? 0)"
        userName.text = user.userName
        
        let attrStr = NSMutableAttributedString.init(string: String(format: "%.2f", user.faceValue),attributes: [.font: UIFont.systemFont(ofSize: 14)])
        attrStr.addAttributes([.font: UIFont(name: "Verdana-Italic", size: 30)!], range: NSRange(location: 0, length: user.faceValue > 10 ? 2 : 1))
        facecValue.attributedText = attrStr
    }
    
    @discardableResult
    func click(_ closure: ((RankView) -> Void)?) -> RankView {
        clickColsure = closure
        return self
    }
    
    @objc private func clickAction() {
        clickColsure?(self)
    }
}

private class EvaluationView: UIView {
    
    private var type = ScoreViewType.single
    
    private var clickClosure: ((EvaluationView) -> Void)?
    
    private lazy var bgView: UIImageView = {
        let view = UIImageView()
        view.image = (type == .single) ? UIImage(named: "face_anly_score_single") : UIImage(named: "face_anly_score_pk")
        return view
    }()
    
    private lazy var btnLabel: UILabel = {
        let view = UILabel()
        view.font = .systemFont(ofSize: 14)
        view.textColor = .initWithRGB(238, 169, 134)
        view.layer.masksToBounds = true
        view.layer.cornerRadius = 15
        view.text = "上传图片"
        view.textAlignment = .center
        view.layer.borderColor = UIColor.initWithRGB(238, 169, 134).cgColor
        view.layer.borderWidth = 1
        return view
    }()
    
    private lazy var aiAnayLabel: UILabel = {
        let view = UILabel()
        view.font = UIFont(name: "Helvetica-Bold", size: 18)
        view.text = (type == .single) ? "AI测颜值" : "颜值PK"
        return view
    }()
    
    private lazy var desLabel: UILabel = {
        let view = UILabel()
        view.textColor = mainColor
        view.font = .systemFont(ofSize: 14)
        view.text = (type == .single) ? "看看你的颜值，魅力值，皮肤状态" : "颜值排行榜，与帅哥美女切磋"
        return view
    }()
    
    init(frame: CGRect, type: ScoreViewType) {
        super.init(frame: frame)
        backgroundColor = .white
        layer.masksToBounds = true
        layer.cornerRadius = 25
        
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(clickAction))
        self.addGestureRecognizer(tap)
        
        self.type = type
        addsubViews([bgView, aiAnayLabel, desLabel, btnLabel])
        
        var y: CGFloat = 20
        bgView.frame = CGRect(x: 16, y: y, width: frame.size.width - 32, height: frame.size.height - 20 - 60)
        y += (frame.size.height - 20 - 60)
        aiAnayLabel.frame = CGRect(x: 16, y: y + 8, width: 200, height: 22)
        btnLabel.frame = CGRect(x: frame.size.width - 16 - 80, y: y + (frame.size.height - y - 30)/2, width: 80, height: 30)
        y += 22 + 8
        desLabel.frame = CGRect(x: 16, y: y, width: 240, height: 20)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    @discardableResult
    func click(_ closure: ((EvaluationView) -> Void)?) -> EvaluationView {
        clickClosure = closure
        return self
    }
    
    @objc private func clickAction() {
        clickClosure?(self)
    }
}

class ScoreVC: MViewController {

    private lazy var bgView: UIImageView = {
        let view = UIImageView()
        view.image = UIImage(named: "face_anly_bg_img")
        return view
    }()
    
    private lazy var rankView: RankView = {
        let view = RankView.init(frame: CGRect(x: 24, y: kStateBarHeight + 16, width: kScreenWidth - 48, height: 80))
        view.click { [weak self] _ in
            self?.navigationController?.pushViewController(RankVC(), animated: true)
            (self?.tabBarController as? MTabBarController)?.hidentabar()
        }
        return view
    }()
    
    let height = (kSafeUseHeight - 96 - 96 - 48)/2
    private lazy var evaluationView: EvaluationView = {
        let view = EvaluationView.init(frame: CGRect(x: 24, y: kNaviBarHeight + 136, width: kScreenWidth - 48, height: height),type: .single)
        view.click { [weak self] _ in
            let imgTool = CLImagePickerTool()
            imgTool.singleImageChooseType = .singlePicture
            imgTool.cl_setupImagePickerWith(MaxImagesCount: 1, superVC: self) { asset, image in
                CLImagePickerTool.convertAssetArrToOriginImage(assetArr: asset, scale: 1) { img, _ in
                    let vc = SingleAnalyzeVC()
                    vc.image = img
                    let tabbar = self?.tabBarController as? MTabBarController
                    tabbar?.hidentabar()
                    self?.navigationController?.pushViewController(vc, animated: true)
                } failedClouse: {
                    self?.view.showToast(text: "既然看到了这个，那应该是出bug了")
                }
            }
//            let vc = SingleAnalyzeVC()
//            let tabbar = self?.tabBarController as? MTabBarController
//            tabbar?.hidentabar()
//            self?.navigationController?.pushViewController(vc, animated: true)
        }
        return view
    }()
    
    private lazy var evaluationView2: EvaluationView = {
        let view = EvaluationView.init(frame: CGRect(x: 24, y: height + 38 + kNaviBarHeight + 136, width: kScreenWidth - 48, height: height), type: .pk)
        view.click { [weak self] _ in
            let vc = RankVC()
            let tabbar = self?.tabBarController as? MTabBarController
            tabbar?.hidentabar()
            self?.navigationController?.pushViewController(vc, animated: true)
        }
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        (self.tabBarController as? MTabBarController)?.showTababr()
        requestFirstRank()
    }
}

extension ScoreVC {
    private func setupUI() {
        view.addsubViews([bgView, rankView, evaluationView, evaluationView2])
        bgView.frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight)
    }
    
    private func requestFirstRank() {
        MoyaNetwork.request(target: BaseApi.topRank) { json, jsonStr in
            let model = User.deserialize(from: json["data"].dictionaryObject)
            self.rankView.user = model
        }
    }
}
